package com.zhouxianglh.p25;

import lombok.Data;

/**
 * 25. K 个一组翻转链表
 * <p>
 * 用递归产生类似堆的效果
 *
 * @author zhouxianglh
 */
public class Solution {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        System.out.println(reverseKGroup(head, 2));
    }

    public static ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) {
            return head;
        }
        ListNode node = change(head, k - 1);
        if (node == null) {
            return head;
        }
        ListNode lastNode = head;
        while (null != lastNode.next) {
            ListNode next = lastNode.next;
            ListNode change = change(lastNode.next, k - 1);
            if (null != change) {
                lastNode.next = change;
                lastNode = next;
            } else {
                break;
            }
        }
        return node;
    }

    public static ListNode change(ListNode node, int flag) {
        ListNode nextNode = node.next;
        if (null == nextNode) {
            return null;
        } else if (flag == 1) {
            node.next = nextNode.next;
            nextNode.next = node;
            return nextNode;
        } else {
            ListNode temp = change(nextNode, flag - 1);
            if (null != temp) {
                node.next = nextNode.next;
                nextNode.next = node;
                return temp;
            } else {
                return null;
            }
        }
    }

    @Data
    public static class ListNode {
        int val;

        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}
